package com.maezia.tdr.common;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.maezia.tdr.common.enums.StatusCodeEnum;
import com.maezia.tdr.common.exception.TokenExpiredException;
import com.maezia.tdr.common.exception.TokenParsingException;
import com.maezia.tdr.domain.po.Dict;
import com.maezia.tdr.service.DictService;
import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.PostConstruct;
import java.security.Key;
import java.util.Date;

@Component
public class JwtTokenProvider {

    @Autowired
    private DictService dictService;

    private Key signKey;

    @PostConstruct
    public void init(){
        byte[] keyBytes = Decoders.BASE64.decode(CommonConstant.TOKEN_SECRET);
        signKey = Keys.hmacShaKeyFor(keyBytes);
    }

    public String generateToken(Object userInfo) {
        JwtBuilder jwtBuilder = Jwts.builder().signWith(signKey, SignatureAlgorithm.HS512);
        jwtBuilder.setSubject(JSONObject.toJSONString(userInfo));
        jwtBuilder.setIssuedAt(DateUtil.date());
        Dict dict = dictService.getByKey(CommonConstant.ACCESS_TOKEN_KEY);
        Long expire = System.currentTimeMillis() + Long.valueOf(dict.getValue()) * 60 * 60 * 1000;
        jwtBuilder.setExpiration(new Date(expire));
        return jwtBuilder.compact();
    }

    public <T> T getUserInfo(String token, Class<T> clazz) throws TokenExpiredException{
        try {
            JwtParser jwtParser = Jwts.parserBuilder().setSigningKey(signKey).build();
            Claims claims = jwtParser.parseClaimsJws(token).getBody();
            if(ObjectUtils.isEmpty(claims)){
                return null;
            }
            return JSONObject.parseObject(claims.getSubject(), clazz);
        }catch (Exception e){
            throw new TokenExpiredException(StatusCodeEnum.TOKEN_EXPIRED);
        }
    }

    public Boolean isExpired(String token) throws TokenParsingException {
        try {
            JwtParser jwtParser = Jwts.parserBuilder().setSigningKey(signKey).build();
            Claims claims = jwtParser.parseClaimsJws(token).getBody();
            if (ObjectUtils.isEmpty(claims)) {
                return true;
            }
            return ObjectUtils.isEmpty(claims.getExpiration()) ? true : DateUtil.date(claims.getExpiration()).before(DateUtil.date());
        }catch (Exception e){
            return true;
        }
    }
}
